package com.taoes.simpledocker.ws.callback;

import cn.hutool.core.util.StrUtil;
import com.github.dockerjava.api.model.Frame;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import javax.websocket.Session;
import java.io.Closeable;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class FileManagementCallback extends AbstractResultCallback<Frame> {


    public FileManagementCallback(Session session) {
        super("容器文件", session);
    }

    @SneakyThrows
    @Override
    public void onStart(Closeable closeable) {
    }

    @SneakyThrows
    @Override
    public void onNext(Frame object) {

        final String content = new String(object.getPayload());

        if (StrUtil.isBlank(content)) {
            return;
        }

        if (StrUtil.startWith(content, "ls ")) {
            return;
        }

        if (StrUtil.startWith(content, "# ")) {
            return;
        }

        HashMap<String, String> response = new HashMap<>();
        Pattern p = Pattern.compile("\\s{1,}|\t");
        Matcher m = p.matcher(content);
        String s = m.replaceAll(",");
        String[] strings = s.split(",");
        if (strings.length < 7) {
            return;
        }
        response.put("permisson", strings[0]);
//        System.out.println(Optional.of(strings[7]).orElse(""));
        response.put("name", strings[7]);
        response.put("size", strings[4]);
        if (StrUtil.startWith(strings[0], "d")) {
            response.put("type","0");
        } else {
            response.put("type","1");

        }
        response.put("modify_time",strings[5] + " " + strings[6]);
        sendMessage(response.toString());
    }

    @Override
    @SneakyThrows
    public void onError(Throwable throwable) {
        sendMessage("ERROR:" + throwable.getMessage());
        this.close();
    }

    @Override
    @SneakyThrows
    public void onComplete() {
        sendMessage("COMPLETE");
        this.close();
    }


}
